<!--
 mode: 表示字典的展示形式
       text文字形式
       icon图标形式
       tag标签形式
       radio单选框形式
       select下拉框行式

 dictCode: 字典编码

 itemValue: 字典项的值

-->
<template>
  <div class="w-100">
    <span v-if="mode === 'text'">{{ dictItem.label }}</span>

    <span v-if="mode === 'icon'">
      <svg-icon v-if="iconClass" :icon-class="iconClass" />
    </span>

    <span v-if="mode === 'tag'">
      <el-tag :type="tag"> <svg-icon v-if="iconClass" :icon-class="iconClass" />{{ dictItem.label }}</el-tag>
    </span>

    <div v-if="mode === 'radio'">
      <el-radio-group v-model="radioValue" @change="handleRadioChange">
        <el-radio v-for="[value, { label, metaEntity }] in dictMap" :key="value" :value="value" size="small">
          <el-tag v-if="metaEntity && isNotEmpty(metaEntity.tag)" class="hand" :type="metaEntity.tag">
            <svg-icon v-if="isNotEmpty(metaEntity.icon)" :icon-class="metaEntity.icon" />
            {{ label }}
          </el-tag>
          <span v-else>{{ label }}</span>
        </el-radio>
      </el-radio-group>
    </div>

    <div v-if="mode === 'select'">
      <el-select v-model="radioValue" :placeholder="dictName" @change="handleRadioChange">
        <el-option v-for="[value, { label }] in dictMap" :key="value" :label="label" :value="value" />
      </el-select>
    </div>
  </div>
</template>

<script setup>
import useStore from '@/store'
import { computed, onMounted, ref, watch } from 'vue'
import { isNotEmpty } from '@/utils/validate'

const { dictStore } = useStore()

const props = defineProps({
  mode: {
    required: true,
    type: String,
    validator(value) {
      return ['text', 'icon', 'tag', 'radio', 'select'].includes(value)
    },
  },
  dictCode: {
    required: true,
    type: String,
  },
  itemValue: {
    required: false,
    type: [String, Number],
  },
})

onMounted(() => {})

// 字典的所有值
const dictMap = computed(() => dictStore.dict.get(props.dictCode) || new Map())

// 默认的字典项
const dictItem = computed(() => dictMap.value.get(props.itemValue + '') || new Map())

// 字典名称
const dictName = computed(() => dictStore.dictLabel && dictStore.dictLabel.get(props.dictCode))

// 标签
const tag = computed(() => (isNotEmpty(dictItem.value?.metaEntity) ? dictItem.value.metaEntity.tag : 'info'))

// 图标
const iconClass = computed(() => (isNotEmpty(dictItem.value?.metaEntity) ? dictItem.value.metaEntity.icon : ''))

const emits = defineEmits(['update:itemValue'])

// 单选，选中的值，包括下拉单选
const radioValue = computed(() => (props.itemValue != null ? props.itemValue + '' : null))

// radio修改事件
function handleRadioChange(value) {
  emits('update:itemValue', value)
}
</script>

<style scoped>
.hamburger {
  display: inline-block;
  vertical-align: middle;
  width: 20px;
  height: 20px;
}

.hamburger.is-active {
  transform: rotate(180deg);
}
</style>
